// index.js
// 获取应用实例
const app = getApp()
const log = require('../../utils/log.js'); 
const api = require('../../config/api.js'); 
const util = require('../../utils/util.js'); 
const hub2 = require('../../utils/Hub2.js');
Page({
  data: { 
    options: '',
    provinces: ["京", "沪", "鄂", "湘", "川", "渝", "粤", "闽", "晋", "黑", "津", "浙", "豫", "赣", "贵", "青", "琼", "宁", "吉", "蒙", "冀", "苏", "皖", "桂", "云", "陕", "甘", "藏", "新", "辽", "鲁"],
    keyNums: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "Q", "W", "E", "R", "T", "Y", "U", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M", "港", "澳", "学"],
    type: ['蓝牌', '新能源', '无牌'],
    typeId: 0,
    isShow: false, //弹窗显示隐藏 键盘
    showList: [], //键盘列表
    showId: '', //键盘ID 1-省份 2-数字
    name: '', //省份
    nums: ['', '', '', '', '', ''], //数字
    history: [], //历史记录
    isPop:false,//弹窗 提示框
    errinfor: '当前车辆未入场，请更换车牌重试',
    curShow: 0,//当前显示1 查询页 2进出无任何显示 3订单页 4订单成功页
    cururl:'',//当前url
    curvipcode: '',//当前vipcode
    showLogin: false,//显示一键登录
    isVipUser: false,//VIP用户
    ShowVIPReg: false,//订单页显示会员注册
    wxCode: '',

    btnCaption: '查询',
    isbindCar: true,
    isSwitch: false,
    isTitcketPop: false,//停车券弹窗
    isPopClass: false,
    checkId: '', //选中的id
    num: 0, //使用积分
    coupon: [],
    clickcoupon: [],
     CP:'',
     RCSJ: null,
     TCSJ: '', 
     HYMD: 0,
     CDMD: 0,
     HYMDSJ: '',
     CDMDSJ: '',
     LocalMD: 0,
     YHQ: 0,
     XSJF: false,
     SYJF: 0,
     YS: 0,
     PaySS: 0.0, 
     PayYF: 0,
     CSSJ: 0,
     BDMDBT: '本地免单',
     //倒计时
     DJS: 90,
     ScanOutYard: false,
     StationName: '',
     bandTitle: '绑定车牌缴费>',
     //收费标准
     isRuleTrue: false,
     //最大使用停车券张数
     useTitcketCount: 0 ,
     de_btn: '--color: #08a3e9;',
     bindcar: '--color: #08a3e9;',
     head: '--color: #75c7ed;',
     b_backimg: '../../img/KC01.png',
     img002: '../../img/002-1.png',
     img003: '../../img/003-1.png',
     img004: '../../img/004-1.png',
     titckimg: '../../img/coupons/1-1.png',
     swiperImg: '../../img/s1.png',
     LQbarCode: '',
     LQsaleName: '',
  },
  // 事件处理函数
  onUnload(){
    // if(app.connection){
    //   app.connection.abortConnection();
    //   app.connection=null;
    // }
  },
  onShow(options){
      if(app.intervalbarcode!=null)
      {
         clearInterval(app.intervalbarcode);
         app.intervalbarcode = null;
      }
      wx.getSystemInfo({
        success: (result) => {
          log.info(result)
          console.log(result)
        },
      })
      // 获取当前小程序的页面栈  
      let pages = getCurrentPages();  // 数组中索引最大的页面--当前页面  
      let currentPage = pages[pages.length-1];  // 打印出当前页面中的 options  
      log.info(currentPage.options);
      console.log(currentPage.options)		//正常打印出 options 值,
      let curUrl = '';
      if(currentPage.options!=null && currentPage.options!='undefined'
      && currentPage.options.scene!=null && currentPage.options.scene!='undefined')
      {
         app.scene = decodeURIComponent(currentPage.options.scene);
      } 
      if(app.scene!='undefined' && app.scene!=null && app.scene!='')
      {
           let scene = util.sceneToObject(app.scene);
           this.load(scene,true); 
      }
      else
      {
          this.load(currentPage.options,false);
      }
      console.log("界面显示");
      if(app.PageName.toUpperCase()==='CARQUERY')
      {
          if(app.connection){
              if(!app.connection.IsConnectioned())
              {
                    setTimeout(() => { 
                      if(!app.connection || !app.connection.IsConnectioned())
                      {
                          let now = new Date();
                          var timeSpan = Math.abs(now - app.startConnectedTime);
                          if(timeSpan>9000)
                          {
                              util.tryHideFullScreenLoading(true);
                              util.showErrorToast('对不起！连接超时，请重新扫码',999999);
                              return;
                          }
                      }
                  }, 10000); 
                  app.connection.connection(api.ApiChatUrl+"/AiYardChat"); 
              }
          }
          else
          { 
              setTimeout(() => { 
                if(!app.connection || !app.connection.IsConnectioned())
                {
                    let now = new Date();
                    var timeSpan = Math.abs(now - app.startConnectedTime);
                    if(timeSpan>9000)
                    {
                        util.tryHideFullScreenLoading(true);
                        util.showErrorToast('对不起！连接超时，请重新扫码',999999);
                        return;
                    }
                }
              }, 10000);
              hub2.initConnection();
              app.connection.connection(api.ApiChatUrl+"/AiYardChat"); 
          }
      }
      else if (app.PageName.toUpperCase()==='SCANOUTYARD' || app.PageName.toUpperCase()==='COUPON')
      {
          setTimeout(() => { 
            if(!app.connection || !app.connection.IsConnectioned())
            {
                let now = new Date();
                var timeSpan = Math.abs(now - app.startConnectedTime);
                if(timeSpan>9000)
                {
                    util.tryHideFullScreenLoading(true);
                    util.showErrorToast('对不起！服务器超时，请重新扫码',999999);
                    return;
                }
            }
          }, 10000);
      }
  },

  onLoad(options) {
    // try
    // {
    //     app.scene = decodeURIComponent(options.scene);
    //     if(app.scene==='undefined' || app.scene===null || app.scene==='')
    //     {
    //         console.log('未获取到小程序参数');     
    //     }
    // }
    // catch(ex)
    // {
    //     console.log('获取参数失败'+JSON.stringify(ex));     
    // }
  },
  load(options,scene)
  {
        app.curthis = this;
        const accountInfo = wx.getAccountInfoSync();
        app.appId = accountInfo.miniProgram.appId;
        this.setData({
            history: wx.getStorageSync('car') ? wx.getStorageSync('car') : [],
            curShow: 0,
            BDMDBT: '本地免单',
        }); 
        app.issceneParams = scene;//是否扫码的小程序码
        app.startConnectedTime = null;
        app.needLoadingRequestCount = 0; 
        app.loadingClose = true;
        app.StationId =0;
        app.StationNo ='';
        app.StationName ='';
        app.BrowserType =0;
        app.TenantId =0;
        app.TenantName = '';
        app.PageName = '';
        app.OpenId ='';
        app.SessionKey='';
        app.ConnectionStatus =0;
        app.SaleId ='';
        app.BillNo ='';
        app.OpenGateTime = null;
        app.OpenGateStatus =false;
        app.interval =null;
        app.curPage ='';
        app.startPay =false;//开始请求支付
        // app.connection =null;
        //算费后
        app.payPaysource =0;
        app.payRecordId =0;
        app.payOpenId ='';
        app.payPlateNo ='';
        app.paySS =0;
        app.payMD =0;
        app.payINTime ='';
        app.payStopTime ='';
        app.payStationId =0;
        app.payEndTime ='';
        app.payOrderTime ='';
        app.fromOutGate ="N";
        app.CDMD =0;
        app.HYMD =0;
        app.OverTime =0;
        //算费后计时器
        app.beginPayTime = new Date();

        app.curPlateNo ='';//当前选择车牌
        app.curPlateColor =1;//当前车牌颜色
        app.curPayCardTypeId =0;//当前车牌交费类型
        app.selectBillNos =[];//当前免单券选择值
        app.canClickticket =true;//允许免单券点击
        app.canQuestServer =true;//允许请求支付订单
        app.selectPayType ='';//选择的支付方式
        //扫码交费返回
        app.hadGateRecvice =false;
        //缴费成功通知次数
        app.NoticeTimes =1;
        app.GetStationTimes =0;
        //停车券列表
        app.ParkingTitckets =[];
        //会员系统发的停车券
        app.ParkingTitckets_KCVIP = [];
        
        this.setData({
          options: options,
          ScanOutYard: false,
        })

      let url = '';
      let vipCode = ""; 
      if(this.data.options && this.data.options.p && this.data.options.p!='')
      {
        url = this.data.options.p;
        app.url = url;
      } 
      else if(this.data.options && this.data.options.o && this.data.options.o!='')
      {
        url = this.data.options.o;
        app.url = url;
      }
      else
      {
          if(app.url && app.url!='')
          {
            url = app.url;
          }
      }
      if(this.data.options && this.data.options.Phone && this.data.options.Phone!='')
      {
        vipCode = this.data.options.Phone; 
        app.VipCode = vipCode;
      }
      else
      {
        if(app.VipCode && app.VipCode!='')
        {
            vipCode = app.VipCode;
        }
      }
      this.setData({cururl: url});
      if(url!='')
      { 
        this.login(url,vipCode);
      }
      else
      {
        try
        { 
          //通过appId获取到场所
          this.login("*"+app.appId+"*",vipCode); 
        }
        catch(err)
        {
          util.showErrorToast('扫码错误，小程序无法使用',999999)
        }
      }

  },
  login(iurl,vipCode)
  {
    util.showFullScreenLoading('正在连接服务器...');
    log.info('login连接服务器......')
    wx.login({
      success: function(res) {
          try
          {
              app.curthis.setData({wxCode: res.code});
              log.info(res.code)
              app.curthis.LoginWX(iurl,vipCode,res.code,'','');
          }
          catch(ex)
          {
              log.error('微信登录错误，需要重新扫码小程序'+ex)
              util.tryHideFullScreenLoading(true);
              util.showErrorToast('登录错误，请重新尝试登录',999999)
          }
      },
      fail: function(err) { 
        log.error('微信登录失败-->'+err)
        util.tryHideFullScreenLoading(true);
        util.showErrorToast('登录错误，请重新尝试登录',999999)
      }
    }); 
  },
  getPhoneNumber: function(e){
    let that = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.checkSession({
        success() {
          let iurl = that.data.cururl;
          let code = that.data.wxCode;
          app.curthis.LoginWX(iurl,'',code,e.detail.encryptedData,e.detail.iv) 
        },
        fail() { 
              wx.login({
                success: function(res) { 
                    that.setData({wxCode: res.code});
                    let iurl = that.data.cururl;
                    app.curthis.LoginWX(iurl,'',res.code,e.detail.encryptedData,e.detail.iv)
                },
                fail: function(err) {
                  util.tryHideFullScreenLoading(true);
                  util.showErrorToast('登录错误，请重新尝试登录',999999)
                }
            }); 
        }
        })
    }
    else
    {
       util.tryHideFullScreenLoading(true);
       util.showErrorToast('登录错误，请重新尝试登录',999999)
    }
  }, 
 
  
  /**微信登录 */
  
  LoginWX(iurl,vipCode,code,encryptedData,iv)
  { 
    app.curthis.setData({isVipUser: false});
    log.info('iurl:'+iurl+'-->vipCode:'+vipCode+'-->code:'+code+'-->encryptedData:'+encryptedData+'-->iv:'+iv)
    util.request2(api.LoginWX, {  
      Code: code,
      VipCode: vipCode,
      encryptedData: encryptedData,
      iv: iv, 
      UrlParams: iurl,
      OpenId: app.OpenId,
      SessionKey: app.SessionKey,
      isMiniParams: app.issceneParams
    }, 'POST').then(function(res){
        log.info(res)
        try
        {
            if (res.stationId>0) {    
                try
                {
                    app.StationId = res.stationId;
                    app.StationNo = res.stationNo
                    app.StationName = res.stationName;
                    app.BrowserType = res.clientType;
                    app.SaleId = res.saleId;
                    app.BillNo = res.billNo;
                    app.TenantId = res.tenantId; 
                    app.TenantName = res.tenantName;
                    app.PageName = res.pageName;
                    wx.setNavigationBarTitle({
                      title: app.TenantName+'停车交费'
                    });
                    // ^OpenID+SessionKey^ 非会员系统
                    // !kCVip2+OpenId+SessionKey! 会员系统获取一次手机号
                    // %kCVip2+newVip+OpenId+SessionKey% 完整会员返回
                    // *kCVip2+OpenId+Phone+SessionKey* 非会员返回
                    if(app.TenantName!=='与好智行')
                    {
                      app.curthis.setData({
                      de_btn: '--color: #fe8d04;',
                      head: '--color: #fcc682;',
                      bindcar: '--color: chocolate;',
                      b_backimg: '../../img/KC02.png',
                      img002: '../../img/002.png',
                      img003: '../../img/003.png',
                      img004: '../../img/004.png',
                      titckimg: '../../img/coupons/1-4.png',
                      swiperImg: '../../img/s4.png'
                      });
                    }
                    else
                    {
                       app.curthis.setData({isbindCar: false});
                    }
                    util.tryHideFullScreenLoading(true); 
                    if(res.openId.startsWith('^') && res.openId.endsWith('^'))
                    {
                        let openStr = res.openId.replace('^','').replace('^','');
                        log.info(util.base64_decode(openStr))
                        let verStr = util.base64_decode(openStr).split('$');
                        app.VipParams = null; 
                        app.OpenId = verStr[1];
                        app.SessionKey = verStr[2];
                        app.isAppLogin = true;
                        app.PhoneNumber = "";
                        if(verStr[0]!="")
                        {
                          app.VipParams = JSON.parse(verStr[0]);
                          app.curthis.setData({showLogin: true,bandTitle:'会员绑定车牌可享受免费2小时'}); 
                          if(app.PageName.toUpperCase()==='SCANOUTYARD')
                          {
                              return;
                          }
                        } 
                    }
                    else if(res.openId.startsWith('!') && res.openId.endsWith('!'))
                    {
                          //会员系统必须显示一键登录获取手机号
                         
                          let openStr2 = res.openId.replace('!','').replace('!','');
                          log.info(util.base64_decode(openStr2))
                          let verStr2 = util.base64_decode(openStr2).split('$');
                          app.VipParams = JSON.parse(verStr2[0]);
                          app.OpenId = verStr2[1];
                          app.SessionKey = verStr2[2];
                          app.PhoneNumber = "";
                          app.NewVip = null; 
                          app.curthis.setData({showLogin: true,bandTitle:'会员绑定车牌可享受免费2小时'}); 
                          if(app.PageName.toUpperCase()==='SCANOUTYARD')
                          {
                            return;
                          }
                    }
                    else if(res.openId.startsWith('*') && res.openId.endsWith('*'))
                    {
                        let openStr3 = res.openId.replace('*','').replace('*','');
                        log.info(util.base64_decode(openStr3))
                        let verStr3 = util.base64_decode(openStr3).split('$');
                        app.NewVip = null; 
                        app.VipParams = JSON.parse(verStr3[0]);
                        app.OpenId = verStr3[1];
                        app.PhoneNumber = verStr3[2];
                        app.SessionKey = verStr3[3];
                        app.curthis.setData({bandTitle:'会员绑定车牌可享受免费2小时'}); 
                        app.isAppLogin = true;
                    }
                    else if(res.openId.startsWith('%') && res.openId.endsWith('%'))
                    { 
                          let openStr4 = res.openId.replace('%','').replace('%','');
                          log.info(util.base64_decode(openStr4))
                          let verStr4 = util.base64_decode(openStr4).split('$');  
                          let VipParams4 = JSON.parse(verStr4[0]);
                          let NewVip4 = JSON.parse(verStr4[1]);
                          let openId4 = verStr4[2];
                          app.SessionKey = verStr4[3];
                          app.OpenId = openId4;//NewVip.member_code; 这里还是传OpenId
                          app.NewVip = NewVip4;
                          app.VipParams = VipParams4; 
                          app.PhoneNumber = NewVip4.telephone;
                          app.curthis.setData({isVipUser: true,bandTitle:'会员绑定车牌可享受免费2小时'});
                          app.isAppLogin = true; 
                    }
                    else
                    { 
                        util.showErrorToast(res.openId,999999);
                        return;
                    }
                    //隐藏一键登录按钮
                    app.curthis.setData({showLogin: false,btnCaption: '查询'});
                    if(app.PageName.toUpperCase()==='CARQUERY')
                    { 
                        app.curthis.setData({curShow: 1}); 
                        hub2.startPayNormal();
                        if(app.NewVip!=null && app.NewVip.licenseplate!=null && app.NewVip.licenseplate!="")
                        {
                          app.curthis.setHistory(app.NewVip.licenseplate);
                        }
                        log.info('成功显示查询页面');
                    }
                    else if(app.PageName.toUpperCase()==='SCANINYARD')
                    {
                        app.curthis.setData({curShow: 2}); 
                        hub2.startOpenGate();
                        log.info('成功显示扫码进出页面');
                    }
                    else if(app.PageName.toUpperCase()==='SCANOUTYARD')
                    {
                        app.curthis.setData({
                          curShow: 0,
                          ScanOutYard: true
                        });
                        app.fromOutGate = "Y"; 
                        hub2.startScanOutYard();
                        log.info('成功显示扫码交费页面');
                    }
                    else  if(app.PageName.toUpperCase()==='COUPON')
                    {
                        wx.setNavigationBarTitle({
                          title: app.TenantName+'领券操作'
                        });
                        app.curthis.setData({
                          curShow: 1,
                          isbindCar: false,
                          btnCaption: '领取'
                        }); 
                        hub2.startPayNormal();
                        log.info('成功显示领券页面');
                    }
                    else if(app.PageName.toUpperCase()==='BARCODE')
                    {
                        //显示生成小程序码
                        let env_version = __wxConfig.envVersion
                        let saleId400 = parseInt(app.SaleId,10);
                        util.request2(api.getBarCodeLQ, {  
                          StationId : app.StationId,
                          SaleId: saleId400,
                          env_version : env_version, 
                         }, 'POST').then(function(res){
                          if (res!="") {    
                              if(res.startsWith('!')){
                                  clearInterval(app.intervalbarcode);
                                  app.intervalbarcode = null;
                                  util.tryHideFullScreenLoading(true);
                                  util.showErrorToast(res.replace('!',''),999999);
                                  return;
                              }
                              let imgurl = '';
                              let saleName = '';
                              if(res.split('$').length>1){
                                 imgurl = res.split('$')[0];
                                 saleName = res.split('$')[1];
                              }
                              else
                              {
                                 imgurl = res;
                                 saleName = ''; 
                              }
                              app.curthis.setData({curShow: 4,LQbarCode: api.ApiRootUrl+'MiniCode/'+imgurl,LQsaleName: saleName}); 
                              //启动计时器循环
                              app.intervalbarcode = setInterval(function(){
                                util.request2(api.getBarCodeLQ, {  
                                  StationId : app.StationId,
                                  SaleId: saleId400,
                                  env_version : env_version, 
                                 }, 'POST').then(function(res){
                                  if (res!="") {    
                                      if(res.startsWith('!')){
                                          clearInterval(app.intervalbarcode);
                                          app.intervalbarcode = null;
                                          util.tryHideFullScreenLoading(true);
                                          util.showErrorToast(res.replace('!',''),999999);
                                          return;
                                      } 
                                      let imgurl2 = '';
                                      let saleName2 = '';
                                      if(res.split('$').length>1){
                                        imgurl2 = res.split('$')[0];
                                        saleName2 = res.split('$')[1];
                                      }
                                      else
                                      {
                                        imgurl2 = res;
                                        saleName2 = ''; 
                                      }
                                      app.curthis.setData({curShow: 4,LQbarCode: api.ApiRootUrl+'MiniCode/'+imgurl2,LQsaleName: saleName2});  
                                  }
                                  else {   
                                    //发生错误
                                    util.tryHideFullScreenLoading(true);
                                    util.showErrorToast('生成领券码错误，请彻底退出小程序重新扫描商家码',999999);
                                    clearInterval(app.intervalbarcode);
                                    app.intervalbarcode = null;
                                    return;
                                  }
                                },
                                function(errmsg){  
                                  util.tryHideFullScreenLoading(true);
                                  util.showErrorToast(errmsg,999999);
                                  clearInterval(app.intervalbarcode);
                                  app.intervalbarcode = null;
                                  return;
                                }
                                ); 
                              },300000);
                          }
                          else {   
                            //发生错误
                            util.tryHideFullScreenLoading(true);
                            util.showErrorToast('生成领券码错误，请彻底退出小程序重新扫描商家码',999999);
                            clearInterval(app.intervalbarcode);
                            app.intervalbarcode = null;
                            return;
                          }
                        },
                        function(errmsg){  
                          util.tryHideFullScreenLoading(true);
                          util.showErrorToast(errmsg,999999);
                          clearInterval(app.intervalbarcode);
                          app.intervalbarcode = null;
                          return;
                        }
                        ); 
                        
                    }
                }
                catch(ex){
                  log.error('登录成功后返回，跳转发生错误1-->'+ex)
                  util.tryHideFullScreenLoading(true);
                  util.showErrorToast('小程序登录错误，请重新扫码',999999); 
                }
            } else {   
              log.info(res.openId)
              util.tryHideFullScreenLoading(true);
              util.showErrorToast(res.openId,999999);
            }
        }
        catch(ex){
          log.error('登录成功后返回，跳转发生错误2-->'+ex)
          util.tryHideFullScreenLoading(true);
          util.showErrorToast('小程序登录错误，请重新扫码',999999); 
        }
    },
    function(errmsg){  
      log.error('登录成功后返回，跳转发生错误3-->'+errmsg)
      util.tryHideFullScreenLoading(true);
      util.showErrorToast(errmsg,999999);
    }
    );
  },
  /**车牌界面部分 */
  ok(){
    this.setData({
      isPop:false
    })
  },
  setHistory(e){//查询缓存
    try
    {
        let data ;
        let query = false;
        if(e.constructor === Object)
        {
          data = e.currentTarget.dataset.name;
          query = true;
        }
        else
        {
          if(e==="" || (e.length!=7 && e.length!=8)){ return ;}
          let typeId = 0;
          if(e.length==8)
          {
            typeId = 1;
          }
          data = {
            nums: e,
            typeId: typeId
          }
        }
        let nums = data.nums;
        let arr=[];
        for(let i in nums){
          arr.push(nums[i]) 
        }
        arr.shift();
        
        this.setData({
          typeId:data.typeId,
          name:data.nums[0],
          nums:arr
        })
        if(query)
        {
          this.search();
        }
    }
    catch(ex)
    {
       log.error('点击历史记录错误：' + ex); 
    }
  },
  search() { //查询
    try
    {
        let nums = this.data.nums;
        nums = nums.join('');
        let data_nums = this.data.name + nums;
        if ((this.data.name!="无" && (this.data.name === '' || this.data.nums[this.data.nums.length - 1] === ''))) {
          wx.showToast({
            title: '请输入完整车辆',
            icon: 'none'
          });
          return false;
        }
        
        if(this.data.typeId!=2){
          let data = {
            nums: data_nums,
            typeId: this.data.typeId
          }
          let history = this.data.history;
          let existsHis = false;
          for (let i in history) {
            if (data.nums == history[i].nums) {
              existsHis = true;
              break;
            }
          }
          if(!existsHis)
          {
          if (history.length > 2) {//只保留3位
            history.pop();
          }
          history.unshift(data);//加入新数据
          this.setData({
            history: history
          })
          wx.setStorageSync('car', history)
          }
        }
        //开始查询
        if(this.data.btnCaption==='领取')
        {
            hub2.couponBill(this.data.name+this.data.nums.join(''));
        }
        else
        {
            hub2.GetSationId(this.data.name+this.data.nums.join(''),6, 0, 0, "", app.fromOutGate);
        }
    } 
    catch(ex)
    {
       log.error('查询历史记录错误：' + ex); 
    }
    // this.setData({
    //   isShow:false,
    //   isPop:true
    // });
    
  },
  clear() { //清除
    let flag = '';
    let nums = this.data.nums;
    if (nums[0] != '') { //清除数字键盘
      for (let i in nums) {
        if (nums[i] != '') {
          flag = i
        }
      }
      nums[flag] = '';
      this.setData({
        nums: nums
      });
    } else { //清除省份键盘
      if (this.data.typeId != 2) {
        this.setData({
          name: '',
          showList: this.data.provinces, //键盘列表
          showId: 1, //键盘ID 1-省份 2-数字
        });
      }
    }
  },
  setName(e) { //设置内容
    if (this.data.showId == 1) { //设置身份
      this.setData({
        name: e.currentTarget.dataset.name
      });
      this.setData({ //输入身份键盘切换为数字
        showId: 2,
        showList: this.data.keyNums
      })
    } else { //设置数字
      let nums = this.data.nums;
      for (let i in nums) {
        if (nums[i] == '') {
          nums[i] = e.currentTarget.dataset.name;
          break;
        }
      }
      this.setData({
        nums: nums
      })
    }
  },
  setIsShow(e) { //弹窗显示隐藏
    let id = this.data.typeId == 2 ? 2 : (e.currentTarget.dataset.id ? e.currentTarget.dataset.id : ''); //1-省份 2-数字
    if (id == '' && this.data.nums[this.data.nums.length - 1] == '') {
      wx.showToast({
        title: '请输入完整车辆',
        icon: 'none'
      });
      return false
    }
    if (id == 2 && this.data.name == '') {
      if (this.data.typeId == 2) {
        return false
      }
      this.setData({
        isShow: id != '' ? true : !this.data.isShow,
        showId: 1,
        showList: this.data.provinces
      })
    } else {
      this.setData({
        isShow: id != '' ? true : !this.data.isShow,
        showId: id,
        showList: id == 1 ? this.data.provinces : (id == 2 ? this.data.keyNums : [])
      })
    }
  },
  submit() {
    if (this.data.nums[this.data.nums.length - 1] == '') {
      wx.showToast({
        title: '请输入完整车辆',
        icon: 'none'
      });
      return false
    }
    this.setData({
      isShow: false
    });
  },
  setType(e) { //设置类型 0-蓝牌 1-新能源 2-无牌
    console.log(e)
    this.setData({
      typeId: e.currentTarget.dataset.id,
      isShow: false, //弹窗显示隐藏
      showList: [], //键盘列表
      showId: '', //键盘ID 1-省份 2-数字
      name: e.currentTarget.dataset.id == 2 ? '无' : '', //省份
      nums: e.currentTarget.dataset.id == 1 ? ['', '', '', '', '', '', ''] : ['', '', '', '', '', ''], //数字
    });
    if(this.data.btnCaption!=='领取')
    { 
        if(this.data.name==="无")
        {
            hub2.GetSationId(this.data.name,6, 0, 0, "", app.fromOutGate);
        }
    }
    else
    {
        if(this.data.name==="无")
        {
            hub2.couponBill(this.data.name+this.data.nums.join(''));
        }
    }
  },

  //下面是订单部分
  setSwitch(e) { //是否使用积分
      this.integral(e.detail.value);
  },
  integral(value) {
      if (value) {
          if(app.NewVip!=null && app.VipParams!=null)
          {
                let mon = 0;
                let score = 0;

                if (app.NewVip.grade == app.VipParams.Vip01) {
                    mon = app.VipParams.mon01;
                    score = app.VipParams.score01;
                }
                else if (app.NewVip.grade == app.VipParams.Vip02) {
                    mon = app.VipParams.mon02;
                    score = app.VipParams.score02;
                }
                else if (app.NewVip.grade == app.VipParams.Vip03) {
                    mon = app.VipParams.mon03;
                    score = app.VipParams.score03;
                }
                if (mon > 0 && score > 0) {
                    let useSoc = (app.paySS / mon) * score;
                    let wxPayss = 0;
                    if (useSoc > app.NewVip.current_bonus) {
                       //积分不够 算出实际扣多少积分
                       useSoc =  Math.floor(app.NewVip.current_bonus / score) *  score;
                       wxPayss = (app.paySS - ((useSoc / score) * mon)).toFixed(2);
                    }
                    //if (useSoc <= app.NewVip.current_bonus) {
                        app.VipUseSoc = "Y"
                        this.setData({
                          num: useSoc,
                          isSwitch: value,
                          PaySS: wxPayss
                        }); 
                    //}
                    //else {
                    //  app.curthis.setData({
                    //    isShow:false,
                    //    isPop:true,
                    //    errinfor: '对不起，您的积分余额不足！', 
                    //  });  
                    //}
                }
                else {
                  this.setData({
                    num: 0,
                    isSwitch: value,
                    PaySS: app.paySS
                  });  
                }
          }
          else
          {
            this.setData({
              num: 0,
              isSwitch: value,
              PaySS: app.paySS
            });  
          }
          // this.setData({
          //     num: parseFloat(this.data.checkId.length * 10),
          //     isSwitch: value
          // })
      } else {
          this.setData({
              num: 0,
              isSwitch: value,
              PaySS: app.paySS
          });
      }
  },
  checkList(e) { //选择优惠券
      let coupon = this.data.coupon;
      let that = this;
      let tDeduType = 0;
      let canUseCount = 99;
      if(app.VipParams!=null)
      {
         //if(app.NewVip==null){return;}
         canUseCount = parseInt(app.VipParams.Ticket01,10);
      } 
      let select = e.detail.value.length;
      if(select>canUseCount)
      {
          app.curthis.setData({
            isShow:false,
            isPop:true,
            errinfor: '本次停车券使用张数已达上限', 
          }); 
          this.setIsPop();
          return; 
      }
      for (let i in coupon) {
          if (e.detail.value.length == 0) {
              coupon[i].tUseStatus = 1;  
          } else {
              let flag = true;
              for (let j in e.detail.value) {
                  if (e.detail.value[j] == coupon[i].ID) {
                      
                      if(tDeduType==0 && tDeduType!=coupon[i].tDeduType){
                         tDeduType = coupon[i].tDeduType;
                      }
                      else if(tDeduType!=coupon[i].tDeduType)
                      {
                        app.curthis.setData({
                          isShow:false,
                          isPop:true,
                          errinfor: '不允许使用不同类型的停车券', 
                        }); 
                        this.setIsPop();
                        return;   
                      }
                      
                      coupon[i].tUseStatus = 2; 
                      flag = false; 
                      break;
                  }
                  if (flag==true) {
                      coupon[i].tUseStatus = 1;
                       
                  }
              }
          }
      }
      let iUse = coupon.filter(o=>o.tUseStatus==2).length;
                      if(iUse>canUseCount)
                      { 
                          app.curthis.setData({
                            isShow:false,
                            isPop:true,
                            errinfor: '本次停车券使用张数已达上限', 
                          }); 
                          this.setIsPop();
                          return; 
                      }
      this.setData({
          checkId: e.detail.value,
          coupon: coupon
      }); 
      this.integral(false);
      let usetitckets = this.data.coupon.filter(o=>o.tUseStatus==2);
      let freeType=1;
      let freeValue=0;
      if(usetitckets && usetitckets.length>0)
      {
        freeType = usetitckets[0].tDeduType; 
        usetitckets.forEach(item=> {
            freeValue += item.tDeduValue;
        }, 0);
      }
      hub2.GetSationId(app.curPlateNo, 4, freeType, freeValue, app.payEndTime, app.fromOutGate);//算费请求
  },
  setIsPop() { //弹窗显示隐藏
      let that = this;
      if (that.data.isTitcketPop) { //隐藏
          setTimeout(function () {
              that.setData({
                  isTitcketPop: !that.data.isTitcketPop,
              });
          }, 300)
          that.setData({
              isPopClass: !that.data.isPopClass,
          });
      } else { //显示
          that.setData({
              isTitcketPop: !that.data.isTitcketPop,
          });
          setTimeout(function () {
              that.setData({
                  isPopClass: !that.data.isPopClass,
              });
          }, 100)
      }
  },
  //以下是车场资讯按钮
  setOnShow(){
    this.onShow();
  },
  showsf(){
     //显示收费标准
     if(app.TenantName!=='与好智行')
     {
         this.showRule();
     }
  },
  showjf(){
    wx.redirectTo({
      url: '/pages/stoprecord/record',
    })
  },
  showyhq(){
    wx.redirectTo({
      url: '/pages/titcket/titckets',
    })  
  },

  submitPay(){
    clearInterval(app.inter);
    app.inter = null;
    util.showFullScreenLoading("支付中，请稍后..");
    let vipcode = ''; 
    if(app.NewVip!=null){
      vipcode = app.NewVip.member_code;
    }
    let bill = "";
    let canUseCount = 99;
    if(app.VipParams!=null)
    { canUseCount = parseInt(app.VipParams.Ticket01,10); }
    let hadUse = 0;
    if (this.data.coupon.length > 0) {
        for (let i = 0; i < this.data.coupon.length; i++) {
          if(this.data.coupon[i].tUseStatus==2)
          {
            if(hadUse>=canUseCount){
               break;
            }
            bill = bill + this.data.coupon[i].ID + ",";
            hadUse = hadUse + 1;
          }
        }
        bill = (bill.substring(bill.length - 1) == ',') ? bill.substring(0, bill.length - 1) : bill; 
    }
    let wxPay = Number(this.data.PaySS).toFixed(2) * 100;
    let socPay = Number(app.paySS - wxPay).toFixed(2) * 100 ;
    let ss = app.paySS*100;
    let md = app.payMD*100;
    let StationId = app.StationId;
    let RecordId = app.payRecordId;
    wx.setStorageSync('StationId', StationId)
    wx.setStorageSync('RecordId', RecordId)
    util.request2(api.settlementOrder, {  
        subAppId : app.appId,
        SS : ss,
        SocPay: socPay,
        WxPay: wxPay,
        MD : md,
        PlateNo : app.payPlateNo,
        StopTime : app.payStopTime,
        CC : 1,
        RecordID : app.payRecordId,
        StationId : app.StationId,
        OpenId : app.payOpenId,
        OverTime : app.payOrderTime,
        PayInTime : app.payINTime,
        PayEndTime : app.payEndTime,
        PayOrderTime : app.payOrderTime,
        VipCode : vipcode,
        VipUseSoc : app.VipUseSoc,
        Bill : bill
    }, 'POST').then(function(res){
        if (res.status==0) {    
            //支付成功
            app.OutTradeNo = res.message; 
            //app.StationId = StationId;
            //app.payRecordId = RecordId;
            util.tryHideFullScreenLoading(true);
            wx.redirectTo({
              url: '/pages/settlement/settlement?OutTradeNo='+res.message+"&StationId="+StationId+"&RecordId="+RecordId+"&From=0",
            })
        } 
        else if(res.status==200)
        {
            app.OutTradeNo = res.message; 
            //app.StationId = StationId;
            //app.payRecordId = RecordId;
            //请求微信支付
            wx.requestPayment({
             nonceStr: res.miniProOrder.nonceStr,
             package: res.miniProOrder.package,
             paySign: res.miniProOrder.paySign,
             signType: res.miniProOrder.signType,
             timeStamp:res.miniProOrder.timeStamp,
             success: function(result){
                wx.redirectTo({
                  url: '/pages/settlement/settlement?OutTradeNo='+res.message+"&StationId="+StationId+"&RecordId="+RecordId+"&From=200",
                }) 
             },
             fail: function(result){
                  let errMsg = result.errMsg;
                  if(errMsg=="requestPayment:fail cancel")
                  {
                    errMsg="您已经取消支付！"
                  }
                  app.curthis.setData({
                    isShow:false,
                    isPop:true,
                    errinfor: errMsg, 
                  });
                  //计时器继续
                  if(app.inter==null)
                  {
                      app.inter = setInterval(function() {
                          app.curthis.setData({ 
                              DJS: app.curthis.data.DJS - 1,
                          });
                          if (app.curthis.data.DJS < 0) {
                              clearInterval(app.inter)
                              app.inter = null;
                              app.curthis.setData({ 
                                  DJS: 90
                              });
                              app.curthis.setData({curShow:1})
                          }
                      }, 1000);
                  }
             }
            }) 
            util.tryHideFullScreenLoading(true);
        }
        else {   
          //发生错误
          util.tryHideFullScreenLoading(true);
          util.showErrorToast(res.message,999999);
        }
    },
    function(errmsg){  
      util.tryHideFullScreenLoading(true);
      util.showErrorToast(errmsg,999999);
    }
    );  
  },
  exitLogin(){
    util.request2(api.loginOut, {  
      OpenId: app.OpenId
    }, 'POST').then(function(res){
       app.curthis.setData({showLogin: true,curShow: 0}); 
      },
      function(errmsg){  
        app.curthis.setData({showLogin: true,curShow: 0});  
      }
    ); 
  },
  bandCar(){
    clearInterval(app.inter)
    app.inter = null;
    if(app.PhoneNumber=="" && app.VipParams!=null)
    {
       app.curthis.setData({showLogin: true,curShow: 0,bandTitle:'会员绑定车牌可享受免费2小时'}); 
       return;
    }
    wx.redirectTo({
      url: '/pages/reg/reg',
    })
  },
   //打开规则提示
  showRule: function () {
  this.setData({
   isRuleTrue: true
  })
  },
  //关闭规则提示
  hideRule: function () {
  this.setData({
   isRuleTrue: false
  })
  },
})
